package com.jblog.core.service.blog.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jblog.core.dao.blog.CalendarArchiveDao;
import com.jblog.core.model.blog.archive.PostCalendarArchive;
import com.jblog.core.service.blog.ArchiveService;

/**
 * ArchiveServiceImpl.java
 * 
 * create at 08/29/2011 11:27:31
 */
@Service
public class ArchiveServiceImpl implements ArchiveService {

    @Autowired
    private CalendarArchiveDao calendarArchiveDao;

    @Override
    public List<PostCalendarArchive> findCalendarArchiveOfPost() {

        return postCalendarArchiveList(calendarArchiveDao.getCalendarArchiveOfPost());
    }

    private List<PostCalendarArchive> postCalendarArchiveList( List<PostCalendarArchive> list) {
        List<PostCalendarArchive> archives;
        Map<String, List<PostCalendarArchive>> archivesMap = new HashMap<String, List<PostCalendarArchive>>();
        for (PostCalendarArchive p : list) {
            if (null != archivesMap.get(p.getYear())) {
                archivesMap.get(p.getYear()).add(p);
            } else {
                archives = new ArrayList<PostCalendarArchive>();
                archives.add(p);
                archivesMap.put(p.getYear(), archives);
            }
        }
        return map2PostCalendarArchiveList(archivesMap);
    }
    
    private List<PostCalendarArchive> map2PostCalendarArchiveList(Map<String, List<PostCalendarArchive>> map) {
        List<PostCalendarArchive> archives = new ArrayList<PostCalendarArchive>();
        for (Map.Entry<String, List<PostCalendarArchive>> e : map.entrySet()) {
            archives.add(new PostCalendarArchive(e.getKey(), e.getValue()));
        }
        return archives;
    }

}
